/**
 * 
 */
package com.shiro.service.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shiro.mapper.RoleMapper;
import com.shiro.mapper.UserRoleMapper;
import com.shiro.pojo.Role;
import com.shiro.pojo.RoleExample;
import com.shiro.pojo.User;
import com.shiro.pojo.UserRole;
import com.shiro.pojo.UserRoleExample;
import com.shiro.service.RoleService;
import com.shiro.service.UserService;

/**
 * @author zyj
 *
 */
@Service
public class RoleServiceImpl implements RoleService {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	@Autowired RoleMapper roleMapper;

	@Override
	public Set<String> listRoleNames(String userName) {
		Set<String> result = new HashSet<>();
		List<Role> roles = listRoles(userName);
		for (Role role : roles) {
			result.add(role.getName());
		}
		return result;
	}

	@Override
	public List<Role> listRoles(String userName) {
		List<Role> roles = new ArrayList<>();
        User user = userService.getByName(userName);
        if(null==user)
            return roles;
         
        roles = listRoles(user);
        return roles;
	}

	@Override
	public List<Role> listRoles(User user) {
		List<Role> roles = new ArrayList<>();
		 
        UserRoleExample example = new UserRoleExample();
         
        example.createCriteria().andUidEqualTo(user.getId());
        List<UserRole> userRoles= userRoleMapper.selectByExample(example);
         
        for (UserRole userRole : userRoles) {
            Role role=roleMapper.selectByPrimaryKey(userRole.getRid());
            roles.add(role);
        }
        return roles;
	}

	@Override
	public List<Role> list() {
		RoleExample example =new RoleExample();
        example.setOrderByClause("id desc");
        return roleMapper.selectByExample(example);
	}

	@Override
	public void add(Role role) {
		roleMapper.insert(role);
	}

	@Override
	public void delete(Long id) {
		roleMapper.deleteByPrimaryKey(id);
	}

	@Override
	public Role get(Long id) {
		return roleMapper.selectByPrimaryKey(id);
	}

	@Override
	public void update(Role role) {
		roleMapper.updateByPrimaryKeySelective(role);
	}

}
